<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\AdminGoodsSalesRequest;
use App\Model\Goods;
use App\Model\Goodssale;
use App\Model\Goodsattr;
use App\Model\Goodstype;
use App\Model\Goodspic;
use App\Model\Goodsbrand;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Redis;
use DB;

class AdminGoodsSaleListController extends Controller
{
    /**
     * 显示促销列表页
     */
    public function AdminSaleList()
    {
    	$sale = Goodssale::select('id', 'goods_id', 'goods_name', 'start_time', 'end_time', 'price', 'promate_price', 'promate_num', 'status')->get();

        foreach ($sale as $v) {

            // dd($v->goods_id);

            //判断是否已经过了促销时间
            if ($v->end_time < date('Y-m-d H:i:s')) {

                //把商品表促销状态改为否
                Goods::where('id', $v['goods_id'])->update(['promate' => 0]);

                //删除促销信息
                Goodssale::where('id', $v->id)->delete();

                //删除Redis中的促销
                $setGoodsKey = 'goods_sale_set_data';
                $hashGoodsKey = 'goods_sale_hash_data:'.$v['goods_id'];

                Redis::sRem($setGoodsKey, $hashGoodsKey);
                Redis::del($hashGoodsKey);

                //判断是否是热销商品
                $good = Goods::find($v['goods_id']);
                if ($good->buy_num < 100) {

                    //删除其在Redis的商品属性
                    $setColorKey = 'goods_set_color_data:'.$v['goods_id'];
                    $setSizeKey = 'goods_set_size_data:'.$v['goods_id'];

                    Redis::del($setColorKey);
                    Redis::del($setSizeKey);

                    //删除其在Redis的图片
                    $setPicKey = 'goods_set_pic_data:'.$v['goods_id'];

                    Redis::del($setPicKey);
                }
                
            }
        }
    	
    	return view('Admin.goods.product-saleslist', ['sale' => $sale]);
    }


    /**
     * 处理禁用促销
     */
    public function AdminSaleStop(Request $req)
    {
    	$id = $req->id;

    	//开启事务
    	DB::beginTransaction();
    	try{

	    	//修改促销表的状态
	    	Goodssale::where('id', $id)->update(['status' => 1]);

	    	$sale = Goodssale::find($id);

	    	$gid = $sale->goods->id;

	    	//修改商品为是否促销
	    	Goods::where('id', $gid)->update(['promate' => 0]);

	    	//提交事务
	    	DB::commit();

    	}catch(\Illuminate\Database\QueryException $e) {
    		//回滚事务
	    	DB::rollback();

	    	return [
	    		'msg' => '禁用失败',
	    		'status' => 404,
    		];

	   	}

	   	//删除Redis的促销商品
	    $setGoodsKey = 'goods_sale_set_data';
	    $hashGoodsKey = 'goods_sale_hash_data:'.$gid;

	    Redis::sRem($setGoodsKey, $hashGoodsKey);
	    Redis::del($hashGoodsKey);

        //查询商品是否为热销
        $good = Goods::find($gid);

        if ($good->buy_num < 100) {

            //删除其在Redis的商品属性
            $setColorKey = 'goods_set_color_data:'.$gid;
            $setSizeKey = 'goods_set_size_data:'.$gid;

            Redis::del($setColorKey);
            Redis::del($setSizeKey);

            //删除其在Redis的图片
            $setPicKey = 'goods_set_pic_data:'.$id;

            Redis::del($setPicKey);
        }

	   	return [
    		'msg' => '禁用成功',
    		'status' => 200,
    	];
    }




    /**
     * 处理启用促销
     */
    public function AdminSaleStart(Request $req)
    {
    	$id = $req->id;

    	//开启事务
    	DB::beginTransaction();
    	try{

	    	//修改促销表的状态
	    	Goodssale::where('id', $id)->update(['status' => 0]);

	    	$sale = Goodssale::find($id);

	    	$gid = $sale->goods->id;

            //修改商品为是否促销
            Goods::where('id', $gid)->update(['promate' => 1]);

            //提交事务
            DB::commit();

        }catch(\Illuminate\Database\QueryException $e) {
            //回滚事务
            DB::rollback();

            return [
                'msg' => '启用失败',
                'status' => 404,
            ];

        }

	   	//将促销写入Redis
	   	$setGoodsKey = 'goods_sale_set_data';
		$hashGoodsKey = 'goods_sale_hash_data:'.$gid;
		Redis::sAdd($setGoodsKey, $hashGoodsKey);
		Redis::hMSet($hashGoodsKey, [
			'id' => $id,
			'goods_id' => $sale->goods_id, 
			'goods_name' => $sale->goods_name, 
			'goods_pic' => $sale->goods->goods_pic,
			'start_time' => $sale->start_time, 
			'end_time' => $sale->end_time, 
			'price' => $sale->price, 
			'promate_price' => $sale->promate_price,
			'promate_num' => $sale->promate_num
		]);

        //判断是否是热销商品
        $good = Goods::find($gid);
        if ($good->buy_num < 100) {
            
            //将商品属性添加进Redis
            $setColorKey = 'goods_set_color_data:'.$gid;
            $setSizeKey = 'goods_set_size_data:'.$gid;

            //查询该商品的所有颜色
            $color = Goodsattr::select('color')->where('goods_id', $gid)->groupBy('color')->get()->toArray();

            //查询该商品的所有尺寸
            $size = Goodsattr::select('size')->where('goods_id', $gid)->groupBy('size')->get()->toArray();

            //遍历把尺寸加入Redis
            foreach ($color as $v) {
                Redis::sAdd($setColorKey, $v['color']);
            }

            //遍历把颜色加入Redis
            foreach ($size as $m) {
                Redis::sAdd($setSizeKey, $m['size']);
            }

            //把商品图片存到Redis
            //查询出该商品的所有图片
            $goodspic = Goodspic::select('pic')->where('goods_id', $gid)->get()->toArray();
            $setPicKey = 'goods_set_pic_data:'.$gid;

            foreach ($goodspic as $p) {
                Redis::sAdd($setPicKey, $p['pic']);
            }
        }

	   	return [
    		'msg' => '启用成功',
    		'status' => 200,
    	];

    }




    /**
     * 处理删除促销
     */
    public function AdminSaleDel(Request $req)
    {
    	$id = $req->id;

    	$sale = Goodssale::find($id);

    	//判断是否促销中
    	if ($sale->status == 0) {
    		return [
    			'msg' => '促销中,不允许删除',
    			'status' => 404,
    		];
    	}

    	$res = Goodssale::where('id', $id)->delete();

    	if (!$res) {
    		return [
    			'msg' => '删除失败',
    			'status' => 404,
    		];
    	}

    	return [
			'msg' => '删除成功',
			'status' => 200,
		];
    }



    /**
     * 显示修改促销页面
     */
    public function AdminSaleEdit(Request $req)
    {

    	$id = $req->id;
    	$sale = Goodssale::find($id);
    	$good = $sale->goods;

    	return view('Admin.goods.product-saleedit', ['good' => $good, 'sale' => $sale]);
    }



    /**
     * 处理修改促销
     */
    public function AdminEditSale(AdminGoodsSalesRequest $req)
    {
    	$gid = $req->input('goods_id');
    	$sid = $req->input('sale_id');
    	$good = Goods::find($gid);
    	
    	$sales['goods_id'] = $gid;
    	$sales['goods_name'] = $good->goods_name;
    	$sales['price'] = $good->price;
    	$sales['start_time'] = $req->input('start_time');
    	
    	$sales['end_time'] = $req->input('end_time');
    	$sales['promate_price'] = $req->input('promate_price');

    	//判断促销价不能小于0不能大于原价
    	if ($sales['promate_price'] <= 0 || $sales['promate_price'] > $sales['price']) {
    		return back()->with('msg', '促销价格不合法');
    	}

    	//查出商品的所有库存
    	$res = Goodsattr::select('reserve')->where('goods_id', $gid)->get();

    	$reser = 0;
    	foreach ($res as $v) {
    		$reser += $v->reserve;
    	}

    	$sales['promate_num'] = $req->input('promate_num');

    	//判断促销数量不能小于等于0
    	if ($sales['promate_num'] < 0) {
    		return back()->with('msg', '促销数量不合法');
    	}

    	//判断促销数量不能大于库存
    	if ($sales['promate_num'] > $reser) {
    		return back()->with('msg', '促销数量不能大于库存');
    	}

    	$sales['status'] = 0;
    	$sales['updated_at'] = date('Y:m:d H:i:s');

    	$lol = Goodssale::where('id', $sid)->update($sales);

    	if (!$lol) {
    		return back()->with('msg', '修改失败');
    	}

    	//先删除Redis
    	$setGoodsKey = 'goods_sale_set_data';
	    $hashGoodsKey = 'goods_sale_hash_data:'.$gid;

	    Redis::sRem($setGoodsKey, $hashGoodsKey);
	    Redis::del($hashGoodsKey);

    	//将促销存入Redis
		Redis::sAdd($setGoodsKey, $hashGoodsKey);
		Redis::hMSet($hashGoodsKey, [
			'id' => $sid,
			'goods_id' => $sales['goods_id'], 
			'goods_name' => $sales['goods_name'], 
			'goods_pic' => $good->goods_pic,
			'start_time' => $sales['start_time'], 
			'end_time' => $sales['end_time'], 
			'price' => $sales['price'], 
			'promate_price' => $sales['promate_price'],
			'promate_num' => $sales['promate_num']
		]);

    	return back()->with('msg', '修改成功');
    }
}
